package com.easycar.common.manager;

import android.os.Handler;
import android.os.Looper;

import com.easycar.common.exception.MethodException;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * 线程池管理工具
 *
 */
public class ThreadPoolManager {
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;
    private  static Handler sHandler;

    private  ThreadPoolManager(){
        sHandler=new Handler(Looper.getMainLooper());
    }
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);
        public Thread newThread(Runnable r) {
            return new Thread(r, "ThreadPoolManager #" + mCount.getAndIncrement());
        }
    };
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);
    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR;
    public  static final    ThreadPoolManager  manager=new ThreadPoolManager();

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

    public   static ThreadPoolManager  getInstance(){
        return  manager;
    }
    public  Executor  getThreadPoolExecutor(){
        return  THREAD_POOL_EXECUTOR;
    }

    /**
     *  异步线程提交
     * @param runnable
     */
    public  void  submitTask(Runnable runnable){
         if(runnable!=null) {
             THREAD_POOL_EXECUTOR.execute(runnable);
         }else {
           throw  new MethodException("ThreadPoolManager  submitTask  Runable  is  null");
         }
    }


    /**
     * 在主线程执行
     * @param runnable  线程
     */
    public  void   executeOnUI(Runnable runnable){
        sHandler.post(runnable);
    }

    /**
     *主线程 延迟执行
     * @param runnable
     * @param delayMillis   时间
     */
    public  void  executeOnUiDelay(Runnable runnable,long delayMillis){
        sHandler.postDelayed(runnable,delayMillis);

    }

    /**
     * 异步线程提交数据
     * @param runnable
     */
    public  void  execute(Runnable runnable){
        THREAD_POOL_EXECUTOR.execute(runnable);
    }



}
